<template>
  <div class="app-container">
    <div class="header-section">
      <h1 class="app-title">WoW团队副本周记</h1>
      <div class="header-controls">
        <div class="left-group">
          <div class="combo-input-container">
            <el-input 
              v-model="newCharName" 
              placeholder="输入角色名"
              class="combo-input"
              @keyup.enter="addCharacter"
            >
              <template #append>
                <el-button 
                  class="add-button"
                  @click="addCharacter"
                  :disabled="!newCharName.trim()"
                >
                  添加角色
                </el-button>
              </template>
            </el-input>
            <el-dropdown trigger="click" class="combo-dropdown">
              <el-button class="dropdown-button">
                <el-icon><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item 
                    v-for="char in characters" 
                    :key="char.name"
                    class="dropdown-item"
                  >
                    <span>{{ char.name }}</span>
                    <div style="flex-grow: 1; min-width: 0">
  <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis">{{ char.name }}</span>
</div>
<el-icon 
  class="delete-icon" 
  @click.stop="deleteCharacter(char.name)"
  style="flex-shrink: 0; color: #F56C6C"
>
  <delete />
</el-icon>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="characters.length === 0" disabled>
                    暂无角色
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <el-button type="danger" @click="showClearConfirm">一键清空</el-button>
        </div>
        <div class="right-group">
          <div class="reset-date" @click="showResetDialog" title="点击可设置更新日期">
            下次更新: {{ nextResetDate }}
          </div>
        </div>
      </div>
    </div>
    
    <div class="raid-container">
      <RaidItem
        v-for="raid in raids"
        :key="raid.id"
        :raid="raid"
        :characters="characters"
        @check-change="handleCheckChange"
      />
    </div>



    <el-dialog v-model="resetDialogVisible" title="设置更新周期">
      <el-select v-model="selectedResetDay" placeholder="选择更新日">
        <el-option
          v-for="day in ['周一', '周二', '周三', '周四', '周五', '周六', '周日']"
          :key="day"
          :label="day"
          :value="day"
        />
      </el-select>
      <template #footer>
        <el-button @click="resetDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateResetDay">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="addCharDialogVisible" title="添加角色">
      <el-input v-model="newCharName" placeholder="输入角色名" />
      <template #footer>
        <el-button @click="addCharDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addCharacter">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="confirmDialogVisible" :title="confirmDialogTitle">
      <span>{{ confirmDialogMessage }}</span>
      <template #footer>
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAction">确认</el-button>
      </template>
    </el-dialog>
    <div class="footer">
      <div class="copyright">
        <span>© 2025 没头脑的老毕</span>
        <a href="https://space.bilibili.com/25160163" target="_blank" class="social-link bilibili" title="Bilibili主页">
          <img src="@/assets/bilibili.ico" alt="Bilibili" class="bilibili-icon">
        </a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, provide } from 'vue'
import { ElMessage } from 'element-plus'

// 对话框显示控制
const addCharDialogVisible = ref(false)
import { Delete, ArrowDown } from '@element-plus/icons-vue'
import RaidItem from './components/RaidItem.vue'
import ICC from '@/assets/ICC.jpg'
import RS from '@/assets/RS.jpg'
import TOC from '@/assets/TOC.jpg'
import 宝库 from '@/assets/宝库.jpg'
import 周常 from '@/assets/周常.jpg'

// 副本数据
const raids = ref([
  { id: '10hicc', name: '10HICC', image: ICC },
  { id: '25hicc', name: '25HICC', image: ICC },
  { id: '10rs', name: '10RS', image: RS },
  { id: '25rs', name: '25RS', image: RS },
  { id: '25toc', name: '25TOC', image: TOC },
  { id: '25htoc', name: '25HTOC', image: TOC },
  { id: '10vault', name: '10宝库', image: 宝库 },
  { id: '25vault', name: '25宝库', image: 宝库 },
  { id: 'weekly', name: '周常', image: 周常 }
])

// 初始化角色状态
function initRaidStatus() {
  const status = {}
  raids.value.forEach(raid => {
    status[raid.id] = {}
    characters.value.forEach(char => {
      status[raid.id][char.name] = false
    })
  })
  return status
}

// 角色和完成状态
const _loadCharacters = () => {
  try {
    const saved = localStorage.getItem('raid-characters')
    return saved ? JSON.parse(saved) : []
  } catch (e) {
    console.error('角色数据加载失败:', e)
    return []
  }
}
const characters = ref(_loadCharacters())

const _loadRaidStatus = () => {
  try {
    const saved = localStorage.getItem('raid-status')
    return saved ? JSON.parse(saved) : {}
  } catch (e) {
    console.error('副本状态加载失败:', e)
    return {}
  }
}
const raidStatus = ref(_loadRaidStatus())

// 提供raidStatus给子组件
provide('raidStatus', raidStatus)

// 对话框状态
const resetDialogVisible = ref(false)
const confirmDialogVisible = ref(false)
const selectedResetDay = ref('周五')
const newCharName = ref('')
const confirmDialogTitle = ref('')
const confirmDialogMessage = ref('')
const pendingAction = ref(null)

// 计算下一次重置日期
const nextResetDate = computed(() => {
  const resetDayMap = {
    '周一': 1, '周二': 2, '周三': 3, '周四': 4,
    '周五': 5, '周六': 6, '周日': 0
  }
  
  const targetDay = resetDayMap[selectedResetDay.value]
  const today = new Date()
  const currentDay = today.getDay()
  
  let daysToAdd = targetDay - currentDay
  if (daysToAdd <= 0) daysToAdd += 7
  
  const nextReset = new Date(today)
  nextReset.setDate(today.getDate() + daysToAdd)
  
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const weekDay = weekDays[nextReset.getDay()]
  
  return `${nextReset.getFullYear()}-${String(nextReset.getMonth() + 1).padStart(2, '0')}-${String(nextReset.getDate()).padStart(2, '0')} ${weekDay}`
})

// 加载保存的数据
onMounted(() => {
  loadSavedData()
})

// 从本地存储加载数据
function loadSavedData() {
  const savedChars = localStorage.getItem('wow-raid-chars')
  const savedStatus = localStorage.getItem('wow-raid-status')
  
  if (savedChars) {
    try {
      characters.value = JSON.parse(savedChars) || []
      raidStatus.value = initRaidStatus()
      
      if (savedStatus) {
        const parsedStatus = JSON.parse(savedStatus)
        // 确保状态数据与当前角色匹配
        for (const raidId in parsedStatus) {
          if (parsedStatus.hasOwnProperty(raidId)) {
            raidStatus.value[raidId] = raidStatus.value[raidId] || {}
            for (const charName in parsedStatus[raidId]) {
              if (characters.value.some(c => c.name === charName)) {
                raidStatus.value[raidId][charName] = parsedStatus[raidId][charName]
              }
            }
          }
        }
      }
    } catch (e) {
      console.error('加载保存数据失败:', e)
      characters.value = []
      raidStatus.value = initRaidStatus()
    }
  } else {
    raidStatus.value = initRaidStatus()
  }
}

// 保存数据到本地存储
function saveData() {
  localStorage.setItem('wow-raid-chars', JSON.stringify(characters.value))
  localStorage.setItem('wow-raid-status', JSON.stringify(raidStatus.value))
}

// 处理勾选状态变化
function handleCheckChange({ raidId, charName, completed }) {
  showConfirmDialog(
    '确认操作',
    `确认【${charName}】的【${raids.value.find(r => r.id === raidId).name}】${completed ? '已' : '未'}完成吗？`,
    () => {
      if (!raidStatus.value[raidId]) raidStatus.value[raidId] = {}
      raidStatus.value[raidId][charName] = completed
      saveData()
    }
  )
}

// 显示重置日对话框
function showResetDialog() {
  resetDialogVisible.value = true
}

// 更新重置日
function updateResetDay() {
  resetDialogVisible.value = false
  // 这里应该实现更新逻辑
}

// 显示添加角色对话框
function showAddCharDialog() {
  newCharName.value = ''
  addCharDialogVisible.value = true
}

// 添加新角色
function addCharacter() {
  if (!newCharName.value.trim()) return
  
  if (characters.value.some(c => c.name === newCharName.value.trim())) {
    ElMessage.warning('角色已存在')
    return
  }
  
  characters.value.push({
    name: newCharName.value.trim(),
    completed: false
  })
  newCharName.value = ''
  saveData()
  ElMessage.success('角色添加成功')
}

// 显示删除角色确认


// 删除角色
function deleteCharacter(charName) {
  // 1. 从角色列表删除
  characters.value = characters.value.filter(c => c.name !== charName)
  
  // 2. 深度清理副本状态
  const newRaidStatus = JSON.parse(JSON.stringify(raidStatus.value))
  Object.keys(newRaidStatus).forEach(raid => {
    delete newRaidStatus[raid][charName]
  })
  raidStatus.value = newRaidStatus
  
  // 3. 同步存储
  localStorage.setItem('raid-characters', JSON.stringify(characters.value))
  localStorage.setItem('raid-status', JSON.stringify(newRaidStatus))
  for (const raidId in raidStatus.value) {
    if (raidStatus.value[raidId][charName]) {
      delete raidStatus.value[raidId][charName]
    }
  }
  
  saveData()
}

// 显示一键清空确认
function showClearConfirm() {
  showConfirmDialog(
    '确认清空',
    '确认清空所有角色的所有副本的完成情况吗？',
    () => {
      raidStatus.value = initRaidStatus()
      saveData()
      // 强制刷新视图
      location.reload()
    }
  )
}

// 显示确认对话框
function showConfirmDialog(title, message, action) {
  confirmDialogTitle.value = title
  confirmDialogMessage.value = message
  pendingAction.value = action
  confirmDialogVisible.value = true
}

// 执行确认的操作
function confirmAction() {
  if (pendingAction.value) pendingAction.value()
  confirmDialogVisible.value = false
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 50%, #0a0a0a 100%);
  font-family: 'Microsoft YaHei', sans-serif;
}

.app-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: 100vh;
  background: rgba(10, 10, 10, 0.9);
  border-left: 1px solid #8B4513;
  border-right: 1px solid #8B4513;
}

.header-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.header-section {
  position: relative;
  padding-bottom: 25px;
  margin-bottom: 40px;
  width: 100%;
}

.header-section::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(to right, transparent, #8B4513, transparent);
}

.app-title {
  color: #FFD700;
  text-align: center;
  margin-bottom: 15px;
  font-size: 2.5em;
  text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
  letter-spacing: 2px;
  font-weight: bold;
}

.header-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-top: 20px;
}

.left-group {
  display: flex;
  align-items: center;
  gap: 20px;
}

.right-group {
  display: flex;
  align-items: center;
}

.reset-date {
  color: #FFD700;
  cursor: pointer;
  font-size: 1.2em;
  padding: 0 10px;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.reset-date:hover {
  color: #FFA500;
}

.raid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 25px;
  margin-bottom: 30px;
}



.combo-input-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.combo-input {
  width: 250px;
}

.add-button {
  background: linear-gradient(145deg, #4CAF50, #2E7D32) !important;
  border-color: #4CAF50 !important;
  color: white !important;
  font-weight: bold;
}

.add-button:hover {
  background: linear-gradient(145deg, #66BB6A, #388E3C) !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.dropdown-button {
  background: rgba(255, 255, 255, 0.1) !important;
  border-color: rgba(255, 255, 255, 0.3) !important;
  color: #FFD700 !important;
  transition: all 0.3s ease;
}

.dropdown-button:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.2);
}

.dropdown-item {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 4px 12px;
  align-items: center;
  padding: 1px 10px;
  width: calc(100% - 10px);
  margin: 0;
}

.delete-icon {
  color: #2196F3;
  cursor: pointer;
  margin-left: 15px;
  font-size: 1.2em;
  transition: all 0.3s ease;
}

.delete-icon:hover {
  color: #64B5F6;
  transform: scale(1.2);
}

.actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

:deep(.el-button) {
  font-weight: bold;
  letter-spacing: 1px;
  border: 2px solid;
}

:deep(.el-button--primary) {
  background: linear-gradient(145deg, #1e90ff, #0066cc);
  border-color: #1e90ff;
  color: white;
}

:deep(.el-button--danger) {
  background: linear-gradient(145deg, #ff4757, #cc0000);
  border-color: #ff4757;
  color: white;
}

:deep(.el-dialog) {
  background: linear-gradient(145deg, #2a2a2a, #1a1a1a);
  border: 2px solid #8B4513;
  border-radius: 10px;
}

:deep(.el-dialog__header) {
  background: linear-gradient(to right, #8B4513, #D2691E);
  color: #FFD700;
  font-weight: bold;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__inner) {
  background: #2a2a2a;
  border: 1px solid #8B4513;
  color: #e6e6e6;
}

:deep(.el-checkbox) {
  margin-left: 10px;  
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #1e90ff;
  border-color: #1e90ff;
}

.footer {
  text-align: center;
  margin-top: 30px;
  padding: 15px 0;
  color: #888;
  font-size: 0.9em;
  border-top: 1px solid #444;
}

.copyright {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.social-link {
  display: inline-flex;
  align-items: center;
  padding: 5px 10px;
  border-radius: 4px;
  text-decoration: none;
  transition: all 0.3s ease;
  font-size: 0.85em;
  font-weight: 500;
}

.social-link.bilibili {
  background-color: rgba(0, 161, 214, 0.1);
  color: #00A1D6;
  border: 1px solid rgba(0, 161, 214, 0.3);
  padding: 8px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bilibili-icon {
  width: 24px;
  height: 24px;
  transition: all 0.3s ease;
  object-fit: contain;
}

.social-link.bilibili:hover {
  background-color: rgba(0, 161, 214, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 161, 214, 0.2);
}

.social-link.bilibili:hover .bilibili-icon {
  transform: scale(1.1);
}
</style>
